MyBlog

Getting Started with GitHub Pages and Jekyll: A Beginner's Guide to Static Websites

How to Build a Website with GitHub Pages and Jekyll

In today's digital landscape, having an online presence is more crucial than ever, whether it's for a personal portfolio, a blog, or a small business website. While many platforms offer website creation, the combination of GitHub Pages and Jekyll stands out for its simplicity, cost-effectiveness, and robust capabilities for static sites. This guide will walk you through everything you need to know to get your first Jekyll website up and running on GitHub Pages, providing a foundational understanding that will serve you well for years to come.

Before diving into the technicalities, let's briefly understand what makes this duo so powerful. GitHub Pages is a free hosting service provided by GitHub that allows you to publish websites directly from your GitHub repositories. It's incredibly convenient for open-source projects, personal sites, and even organizational documentation. Jekyll, on the other hand, is a static site generator. This means it takes your plain text content, written in formats like Markdown, and transforms it into a complete, ready-to-publish static website. Unlike dynamic websites that rely on databases and server-side scripting, static sites are fast, secure, and require minimal maintenance. They're also incredibly scalable and can handle high traffic volumes with ease.

The beauty of Jekyll lies in its simplicity and flexibility. You write your content in Markdown, which is an easy-to-learn plaintext formatting syntax, and Jekyll handles the rest, converting it into HTML. This separation of content and presentation allows you to focus on your writing without getting bogged down in intricate web design details. Furthermore, Jekyll supports themes, plugins, and custom layouts, giving you ample room for customization as your needs evolve. This guide is designed to be evergreen, providing timeless solutions to common questions and challenges faced by anyone looking to build a static website. We'll cover everything from the initial setup to customizing your site and deploying it seamlessly, ensuring you have a clear roadmap for success.

What are the Prerequisites for Building a Jekyll Site?

Before you embark on your Jekyll journey, there are a few essential tools and accounts you'll need. These prerequisites ensure a smooth setup and deployment process.

How to Install Ruby on Your System?

The installation process for Ruby varies slightly depending on your operating system. Here's a general guide:

For macOS:

macOS comes with a version of Ruby pre-installed, but it's often an older version. It's highly recommended to use a version manager like RVM (Ruby Version Manager) or rbenv to install and manage multiple Ruby versions. This prevents conflicts with the system Ruby and gives you more control.

  1. Using Homebrew (Recommended): If you don't have Homebrew, install it first:
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  2. Then, install rbenv:
    brew install rbenv ruby-build
  3. Add rbenv to your shell startup:
    echo 'eval "$(rbenv init -)"' >> ~/.zshrc
    (or ~/.bash_profile if you use Bash)
  4. Restart your terminal or run
    source ~/.zshrc
  5. Install the latest stable Ruby version:
    rbenv install 3.2.2
    (replace with the latest stable version)
  6. Set it as your global Ruby version:
    rbenv global 3.2.2

For Windows:

The easiest way to install Ruby on Windows is using RubyInstaller for Windows.

  1. Download the latest Ruby+Devkit version from rubyinstaller.org/downloads/.
  2. Run the installer and follow the prompts. Make sure to check the box for "Add Ruby executables to your PATH" during installation.
  3. After installation, open a new command prompt or PowerShell window and run the RubyInstaller Development Kit installation by typing:
    ridk install
  4. Follow the prompts to install MSYS2 and the required toolchain.

For Linux:

Similar to macOS, it's best to use a version manager like rbenv or RVM.

  1. Using rbenv:
  2. Install dependencies:
    sudo apt-get install autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm6 libgdbm-dev
    (for Debian/Ubuntu-based systems)
  3. Clone rbenv:
    git clone https://github.com/rbenv/rbenv.git ~/.rbenv
  4. Add rbenv to your PATH:
    echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
  5. Add rbenv init to your shell startup:
    echo 'eval "$(rbenv init -)"' >> ~/.bashrc
  6. Restart your terminal or run
    source ~/.bashrc
  7. Install ruby-build:
    git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
  8. Install the latest stable Ruby version:
    rbenv install 3.2.2
  9. Set it as your global Ruby version:
    rbenv global 3.2.2

After installing Ruby, you can verify your installation by opening a new terminal or command prompt and typing:

ruby -v
This should output the installed Ruby version.

How Do I Install Jekyll?

Once Ruby is installed and configured, installing Jekyll is straightforward using Ruby's package manager, RubyGems.

  1. Open your terminal or command prompt.
  2. Run the following command:
    gem install jekyll bundler

The bundler gem is also installed as it helps manage your project's dependencies, ensuring that all necessary gems for Jekyll and your site are installed correctly. After the installation completes, you can verify Jekyll's installation by typing:

jekyll -v
This should display the Jekyll version. If you encounter any errors, double-check your Ruby installation and PATH configuration.

What are the Steps to Create Your First Jekyll Site?

Now that you have all the prerequisites in place, let's create your very first Jekyll site. This process involves using the Jekyll command-line interface (CLI) to generate a new project.

  1. Navigate to Your Desired Directory: Open your terminal or command prompt and use the cd command to go to the directory where you want to create your website. For example, if you want to create it in your documents folder, you might type:
    cd ~/Documents
  2. Create a New Jekyll Site: Run the following command, replacing my-first-jekyll-site with your desired project name:
    jekyll new my-first-jekyll-site
    This command will create a new directory with the specified name and populate it with a basic Jekyll site structure, including default files and configurations.
  3. Navigate into Your New Site's Directory:
    cd my-first-jekyll-site
  4. Serve Your Site Locally: To see your site in action on your local machine, run:
    bundle exec jekyll serve
    This command will start a local web server, and you'll typically see an output indicating the address where your site is running (e.g., Server address: http://127.0.0.1:4000/). Open your web browser and navigate to that address. You should see the default Jekyll theme with a sample post. The bundle exec prefix ensures that Jekyll uses the gems specified in your project's Gemfile, avoiding potential version conflicts.

Congratulations! You've successfully created and served your first Jekyll site locally. This local server is incredibly useful for development, allowing you to see changes in real-time as you modify your content and design.

How Do I Understand the Jekyll Site Structure?

When you create a new Jekyll site, it comes with a predefined directory structure. Understanding these directories and files is crucial for effectively managing and customizing your website.

Directory/File Description
_config.yml The primary configuration file for your Jekyll site. This is where you set global variables, site metadata, permalinks, and plugin settings. You'll frequently modify this file to customize your site's behavior.
_posts/ Contains all your blog posts. Each post is a Markdown file with a specific naming convention (YYYY-MM-DD-title.md or .markdown).
_layouts/ Houses the HTML templates (layouts) that define the structure of different types of pages on your site. For example, you might have a post.html layout for blog posts and a page.html layout for static pages.
_includes/ Stores reusable snippets of HTML code that you can include in your layouts or posts. This promotes modularity and reduces redundancy (e.g., a navigation bar, a footer, or social media links).
_sass/ Contains your Sass/SCSS files for styling your website. Jekyll processes these files into standard CSS.
assets/ A common directory for static assets like images, JavaScript files, and additional CSS.
index.html The main index file for your site, typically using a layout to display the homepage content.
Gemfile Specifies the Ruby gems (libraries) your Jekyll project depends on. Bundler uses this file to ensure all necessary gems are installed.
Gemfile.lock Automatically generated by Bundler, this file records the exact versions of the gems used in your project, ensuring consistent builds across different environments.

The files and directories starting with an underscore (_) are special to Jekyll and are not directly output to your published site. They are processed by Jekyll to generate the final static HTML files.

How Do I Create a New Page and Layout in Jekyll?

One of the core strengths of Jekyll is its ability to create custom pages and apply different layouts. Let's explore how to do this.

Creating a New Page

To create a new static page, simply create an HTML or Markdown file in the root directory of your Jekyll project (or within any subfolder if you want to organize them).

  1. Create a new file: For example, create a file named about.md in your root directory.
  2. Add Front Matter: At the top of your file, you need to add "Front Matter." This is a block of YAML (YAML Ain't Markup Language) data delimited by triple-dashed lines. Front Matter allows you to set variables for your page, such as the title, layout, and any custom data you need.
---
layout: page
title: About Us
permalink: /about/
---

This is the content of my About page.
You can write in Markdown here!

In this example:

If you don't specify a layout, Jekyll will default to the one defined in your _config.yml or no layout if none is specified globally. After creating this file, save it and run bundle exec jekyll serve again (if it's not already running). You should now be able to access your new page at http://127.0.0.1:4000/about/ (or whatever your local server address is).

Creating a New Layout

Layouts define the overall structure and presentation of your pages. You can create custom layouts in the _layouts directory.

  1. Create a new layout file: For instance, let's create a custom layout for a portfolio page. In the _layouts directory, create a new file named portfolio.html.
  2. Add HTML structure: Inside portfolio.html, you'll define the HTML structure. Crucially, you'll use the {{ content }} liquid tag where the actual content of your Markdown or HTML page will be injected.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ page.title }} | My Portfolio</title>
    <link rel="stylesheet" href="/assets/css/style.css">
</head>
<body>
    <header>
        <nav>
            <ul>
                <li><a href="/">Home</a></li>
                <li><a href="/about/">About</a></li>
                <li><a href="/portfolio/">Portfolio</a></li>
            </ul>
        </nav>
    </header>

    <main>
        {{ content }}
    </main>

    <footer>
        <p>© 2025 My Portfolio. All rights reserved.</p>
    </footer>
</body>
</html>

Now, when you create a page and set layout: portfolio in its Front Matter, Jekyll will wrap the page's content within this portfolio.html structure. The {{ page.title }} liquid tag dynamically inserts the title from your page's Front Matter. This modular approach allows you to maintain consistent branding and navigation across your site while easily updating content.

How Do I Publish My Jekyll Site to GitHub Pages?

Publishing your Jekyll site to GitHub Pages is the final and most exciting step. GitHub Pages offers two main types of sites: User/Organization Pages and Project Pages.

For this guide, we'll focus on setting up a User Page, which is common for personal blogs and portfolios. The steps are similar for Project Pages, with a slight difference in repository naming and branch selection.

  1. Create a New Repository on GitHub:
    • Go to github.com/new.
    • For the Repository name, enter your-github-username.github.io (replace your-github-username with your actual GitHub username).
    • Choose "Public" (GitHub Pages works best with public repositories, though private repos with GitHub Pro also support it).
    • Do not initialize with a README, .gitignore, or license at this stage, as you'll be pushing your existing Jekyll site.
    • Click "Create repository."
  2. Initialize Your Local Jekyll Site as a Git Repository:

    Navigate to your Jekyll project's root directory in your terminal (e.g., cd my-first-jekyll-site).

    git init

    This command initializes an empty Git repository in your current directory.

  3. Add All Your Files to the Staging Area:
    git add .

    The . tells Git to add all files and directories in the current directory to the staging area.

  4. Commit Your Changes:
    git commit -m "Initial Jekyll site commit"

    This creates a new commit with all the staged changes and a descriptive message.

  5. Connect Your Local Repository to Your GitHub Repository:

    Replace your-github-username with your actual GitHub username.

    git remote add origin https://github.com/your-github-username/your-github-username.github.io.git

    This command tells Git about the remote GitHub repository where you want to push your code.

  6. Push Your Local Repository to GitHub:
    git push -u origin main

    This command pushes your local main branch (or master if you initialized your project with an older Git version) to the origin remote. The -u flag sets the upstream, so future pushes can simply be git push.

After pushing your code, it might take a few minutes for GitHub Pages to build and deploy your site. You can monitor the deployment status by going to your repository on GitHub, then navigating to "Settings" -> "Pages." Under "Branch," ensure your source is set to main (or master) and the root directory. You should see a message indicating your site is published, along with the URL.

How Can I Customize My Jekyll Site?

Customizing your Jekyll site goes beyond just adding pages and layouts. It involves tweaking the appearance, adding functionality, and integrating various services. Here are some key areas for customization:

Modifying the _config.yml File

The _config.yml file is your central hub for site-wide settings. You can modify various parameters here:

Any changes to _config.yml require restarting your Jekyll server for them to take effect. If you're running bundle exec jekyll serve, you'll need to stop it (Ctrl+C) and run it again.

Styling with SCSS and CSS

Jekyll supports Sass (SCSS syntax) out of the box, which is a powerful CSS preprocessor that allows for variables, nesting, mixins, and more organized stylesheets. Your default Jekyll project includes a _sass directory. You can create your .scss files here, and Jekyll will automatically compile them into a single CSS file (usually style.css) in your assets/css directory.

To link your stylesheet in your layout files (e.g., default.html or page.html in _layouts), you'd typically use a line like this in the <head> section:

<link rel="stylesheet" href="{{ "/assets/css/style.css" | relative_url }}">

The relative_url filter is important as it ensures the correct path is generated when your site is served from a subdirectory on GitHub Pages (e.g., for Project Pages).

Adding Posts to Your Blog

Your blog posts live in the _posts directory. Each post must follow the naming convention YYYY-MM-DD-title.md (or .markdown). Similar to pages, each post requires Front Matter at the top.

---
layout: post
title: My First Blog Post
date: 2025-07-28 10:00:00 +0700
categories: [digital-marketing, content-creation]
---

This is the content of my very first blog post.
I'm excited to share my thoughts here!

You can write the body of your post using Markdown, which provides a simple and effective way to format text, add headings, lists, links, and images.

Using Includes for Reusable Content

The _includes directory is for snippets of HTML that you want to reuse across multiple pages or layouts. This is excellent for elements like navigation menus, footers, social media links, or author bios. For example, if you have a navigation.html file in _includes:

<nav>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/blog/">Blog</a></li>
        <li><a href="/contact/">Contact</a></li>
    </ul>
</nav>

You can include it in any layout or page using the Liquid include tag:

{% include navigation.html %}

This makes your code more modular, easier to maintain, and ensures consistency across your site.

What are Some Advanced Jekyll Tips for Better Websites?

Once you're comfortable with the basics, consider these advanced tips to enhance your Jekyll site.

Using Data Files

Jekyll allows you to store data in YAML, JSON, or CSV files within a _data directory. This is incredibly useful for managing structured content that isn't a post or a page, such as team members, product lists, or testimonials. For example, you could have a _data/members.yml file:

- name: Alice Smith
  title: Lead Developer
  bio: Alice specializes in front-end development.
- name: Bob Johnson
  title: UI/UX Designer
  bio: Bob focuses on user-centric design.

You can then iterate over this data in your templates using Liquid:

<ul>
    {% for member in site.data.members %}
        <li>
            <h3>{{ member.name }}</h3>
            <p>{{ member.title }}</p>
            <p>{{ member.bio }}</p>
        </li>
    {% endfor %}
</ul>

This separation of data from content and presentation significantly improves site maintainability, especially for content that changes frequently or is used in multiple places.

Implementing Pagination for Blog Posts

For blogs with many posts, pagination is essential for better user experience and performance. Jekyll has built-in support for pagination. You'll need to enable it in your _config.yml:

paginate: 5 # Number of posts per page
paginate_path: "/blog/page:num/"

Then, in your index or blog page layout, you'll use the paginator object to loop through posts and generate navigation links:

{% for post in paginator.posts %}
    <h2><a href="{{ post.url | relative_url }}">{{ post.title }}</a></h2>
    <p>{{ post.excerpt }}</p>
{% endfor %}

<!-- Pagination links -->
{% if paginator.total_pages > 1 %}
    <div class="pagination">
        {% if paginator.previous_page %}
            <a href="{{ paginator.previous_page_path | relative_url }}">Previous</a>
        {% else %}
            <span>Previous</span>
        {% endif %}

        {% for page in (1..paginator.total_pages) %}
            {% if page == paginator.page %}
                <em>{{ page }}</em>
            {% else %}
                <a href="{{ site.paginate_path | replace: ':num', page | relative_url }}">{{ page }}</a>
            {% endif %}
        {% endfor %}

        {% if paginator.next_page %}
            <a href="{{ paginator.next_page_path | relative_url }}">Next</a>
        {% else %}
            <span>Next</span>
        {% endif %}
    </div>
{% endif %}

This automatically generates numbered pages, making your blog more navigable and performant by loading only a subset of posts per page.

Integrating with Analytics (e.g., Google Analytics)

To track your website's traffic and user behavior, you'll want to integrate analytics. The simplest way is to add your analytics tracking code to your default layout file (e.g., default.html) within the <head> tags. For Google Analytics, this involves copying the provided snippet from your Google Analytics property settings.

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-YOUR_MEASUREMENT_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-YOUR_MEASUREMENT_ID');
</script>

Replace G-YOUR_MEASUREMENT_ID with your actual Google Analytics Measurement ID. This ensures that every page using this layout will track visitor data.

Optimizing for Search Engines (SEO)

While static sites are inherently SEO-friendly due to their speed and crawlability, you can further optimize your Jekyll site:

What Are the Benefits of Using GitHub Pages and Jekyll?

The combination of GitHub Pages and Jekyll offers a compelling set of advantages, making it an excellent choice for a wide range of web projects.

What are the Limitations to Consider?

While GitHub Pages and Jekyll offer many advantages, it's important to be aware of their limitations:

Continuing Your Jekyll Journey: Beyond the Basics

Building your first Jekyll site with GitHub Pages is just the beginning. The Jekyll ecosystem is rich with possibilities for further customization and enhancement.

Exploring Jekyll Themes

While the default Jekyll theme is functional, a vibrant community has created countless open-source Jekyll themes that you can easily integrate. These themes range from minimal to highly feature-rich, catering to various needs like portfolios, magazines, or e-commerce showcases. Websites like jekyllthemes.org offer a wide selection.

To use a theme, you typically clone its repository, copy its files into your Jekyll project, and adapt your _config.yml and content accordingly. Many themes provide detailed installation instructions.

Leveraging Jekyll Plugins

Jekyll plugins extend Jekyll's core functionality. While GitHub Pages has restrictions, many useful plugins are officially supported or can be used with custom deployment workflows.

To use a plugin, add it to your Gemfile and your _config.yml, then run bundle install. Remember to check if the plugin is supported by GitHub Pages or if a custom build process is required.

Integrating with Third-Party Services

Since Jekyll builds static sites, you often rely on third-party services to add dynamic features:

These integrations typically involve embedding JavaScript snippets or using APIs within your Jekyll templates.

Automating Deployments with GitHub Actions

While pushing to the main branch of your-username.github.io triggers a GitHub Pages build, for more complex scenarios, especially with unsupported Jekyll plugins or custom build steps, GitHub Actions can automate your deployment workflow.

GitHub Actions allows you to define custom workflows that run automatically when certain events occur (e.g., a push to your repository). You can create a workflow that:

This gives you ultimate control over your Jekyll build process, enabling the use of any plugin or build script you desire, and ensuring a consistent deployment every time.

What are the Best Practices for Maintaining Your Jekyll Site?

Maintaining a Jekyll site is generally low-effort, but following some best practices can ensure its longevity and performance.

By adhering to these practices, you can ensure your Jekyll site remains fast, secure, and easy to manage for the long term. The simplicity of static site generation combined with the power of Git and GitHub Pages makes for a robust and enduring web publishing solution.